<template>
    <canvas id="canvas" ></canvas>
</template>

<script>
export default {
  data() {
    return {
    };
  },
  mounted() {
    this.initCanvas();
  },
  methods: {
    initCanvas() {
      var canvas = document.getElementById('canvas'),
        w = canvas.width = window.innerWidth,
        h = canvas.height = window.innerHeight,
        ctx = canvas.getContext('2d');
      var size = 38;
      var arr = [];
      class ball {
        constructor() {
          this.x = r(w - 160) + 60;
          this.y = r(h - 160) + 60;
          this.r = r(30) + 10;
          this.color = "#" + parseInt(Math.random() * 0xffffff).toString(16);
          this.xSpeed = r(2) + 1;
          this.ySpeed = r(2) + 1;
        }
        show() {
          this.run();
          drawCircle(this.x, this.y, this.r, this.color);
        }
        run() {
          if (this.x - this.r <= 0 || this.x + this.r >= w) {
            this.xSpeed = -this.xSpeed;
          }
          this.x = this.x + this.xSpeed;
          if (this.y - this.r <= 0 || this.y + this.r >= h) {
            this.ySpeed = -this.ySpeed;
          }
          this.y = this.y + this.ySpeed;
        }
      }
//去掉后每次刷新页面出现新的球体但不会运动
      setInterval(() => {
        ctx.clearRect(0, 0, w, h);
        for (var i = 0; i < arr.length; i++) {
          arr[i].show();
        }
      }, 10);
      function drawCircle(x, y, r, color) {
        ctx.beginPath();
        ctx.arc(x, y, r, 0, Math.PI * 2);
        ctx.fillStyle = color;
        ctx.fill();
      }
      function r(num) {
        return parseInt(Math.random() * num);
      }
      function start() {
        for (var i = 0; i < size; i++) {
          var Ball = new ball();
          arr.push(Ball);
          Ball.show();
        }
      }
      start();
    },
  },
};
</script>
<style scoped>
</style>
